import pymssql

database_address = "127.0.0.1:53495"
user = "sa"
password = "ljr121099"
database_name = "Test"

class sql_database:
    def __init__(self, host=database_address, user=user, password=password, name=database_name, charset='utf8'):
        self.host = host
        self.user = user
        self.password = password
        self.name = name
        self.charset = charset
        self.database = None
    def connet(self):
        self.database = pymssql.connect(host=self.host,user=self.user,password=self.password,database=self.name,charset='utf8')
        return self.database is not None
    def add_record(self, table, **kwargs):
        items = ""
        vals = ""
        for item in kwargs:
            items += item + ','
            vals += str(kwargs[item]) + ','
        spl = "INSERT INTO %s(%s) VALUES (%s)"%(table, items[:-1], vals[:-1])
        cursor = self.database.cursor()
        cursor.execute(spl)
        database.database.commit()
        
if __name__ == '__main__':
    database = sql_database()
    print("连接数据库：", database.connet())
    for i in range(0, 100):
        database.add_record("test_table", upload_time="getdate()", raw="\'测试数据-%d\'"%(i))
'''
if __name__ == '__main__':
    database = sql_database()
    print(database.connet())
    cursor = database.database.cursor()
    for i in range(0, 100):
        cursor.execute("INSERT INTO test_table(upload_time, raw) VALUES (getdate() ,'sql_database-%d')"%(i))   #执行sql语句
    database.database.commit()  #提交
'''
'''
if __name__ == '__main__':
    database = sql_database()
    print(database.connet())
    cursor = database.database.cursor()
    cursor.execute("SELECT * FROM test_table")   #执行sql语句
    s = cursor.fetchone()
    print(s)
    while s:
        s = cursor.fetchone()
        print(s)
'''

